import axios from 'axios'
import qs from 'qs'
import merge from 'lodash/merge'
import { message } from 'ant-design-vue';
// import { Message, MessageBox } from 'element-ui'

const http = axios.create({
  timeout: 1000 * 90,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

/**
 * 请求拦截 请求头如果没带 token 参数，则会默认添加
 */
http.interceptors.request.use(config => {
  if (!config.headers['token']) {
    // config.headers['token'] = Vue.cookie.get('token') // 请求头带上token
  }
  config.headers['Authorization'] = 'base eyJhbGciOiJSUzI1NiJ9.ZXlKaGJHY2lPaUpTVXpJMU5pSjkuZXlKemRXSWlPaUpoWkcxcGJpSXNJbkpsWm5KbGMyaEVZWFJsSWpveE5qWTRNakU0TkRjMU1UUXdMQ0pwYzNNaU9pSlVSRVlnUWtGVFJTSXNJbVY0Y0NJNk1UWTJPREl4Tmpjek5Td2lhV0YwSWpveE5qWTRNakUyTmpjMUxDSmhkWFJvYjNKcGRHbGxjeUk2SWpWaU5qWmxZMlkwTldRMk16UXhOVGxoTURnME5qZzRPVGhpTVdJek1qRTNJbjAuTmJLYVlSdFdxdEJTb19la2hYRnVkYnhfam9oWllDTlNNT3NQYVV3X1lkcmJlUjNnMzlsU2dpTGlveUd1S09LUHVvamZuelZZVzJsVEt0S1FDRHUya0l1QnIxMjNhVmxoWGhaXzg5RXBsdm9DdkdRQWQ1RGdTN0RIVWdLVzhQTHlFdi16Z1BUeWNoT2w1eXVUN1NLNXpLYkl4bkVMbVU1TGZ5Y1NfTnJXYXlkMzdadTl4Y2tBZmhlRm9mNzVrWlpISWI2dVQyWjFRcjFhcjE5Vm1xXzlnUndNUnJVMW1YeC1nOUZSY0JuRlJOT1FxNTBNS2s0S1N0NVVNUFhUUlFWZ2JzQ2NaaUw2SHAxRmRrZVV6NXA2V3MxeXE4TG9JUENUTzN2SUFGZEhTRWs3X3dlb0Z1bEIyRjVTdk5IbjFVU2tWNXM1dGVielQxNG9odGUzQ1puWHpB.nsnY0UPgPPlpOyfVITUgMPfNU6zjLWHBx2UQwPEmHjp_JSRtXa49nAZ72tQ6bgYCWRPbhRPyCLbQtOdA2Us06mMUJw0qDKPuY9-A1i8Zm30LW_oQNaMi2XGmkENSxyhYKEntlEg1WbFBmBzHBSBTmRhDdl6czTaqxjccq5MtWoCi5bvxrg_RajkXAEoPrjFDt4-kLjsoVheDoKl62zwPddcfneu7xS3Js0lwNc0-p-wekrtNVOeTY23pbfZb8ZyzOjOa2DaLlCKGJQvRnBYL7UTav-FUQnIGanLoZAaYRADyPZViyaKsktxcvMqIJccZR8gykhnFuavvjD-efj_P9w'
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  if (response.data) {
    if (response.data.code === 900) { // 产品未注册
      // router.push({ name: 'license' })
      message.error('产品未注册,请联系开发商', 3);
    } else if (response.data.code === 401) {
      message.error('请联系后台人员处理', 3);
    }
  }

  return response
}, error => {
  if (error.response && error.response.data && (error.response.data.message || '').indexOf('请联系开发商') > -1) {
    // router.push({ name: 'license' })
    message.error('产品未注册,请联系开发商', 3);
  }
  return Promise.reject(error)
})

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : window.SITE_CONFIG.baseUrl) + actionName
  return 'http://172.16.119.28:8086' + actionName;
}

http.adornFlinkUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : 'http://172.16.119.29:8081') + actionName
  // 中航IP
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : 'http://172.30.131.109:8083') + actionName

  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : 'http://172.16.12.99:8083') + actionName
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : 'http://172.16.12.99:8084') + actionName
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : 'http://172.16.12.99:8085') + actionName
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : 'http://172.16.119.28:8086') + actionName
  return 'http://172.16.119.28:8086' + actionName;
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    't': new Date().getTime()
  }
  return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
  var defaults = {
    't': new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

/***
 * 下载文件
 * @param url
 * @param data
 * @param fileName
 */
http.download = (url = '', data = '', fileName = '', that) => {
  http({
    method: 'post',
    url: http.adornUrl(url),
    data: data,
    responseType: 'blob',
    timeout: 60 * 1000 * 30
  }).then(function (res) {
    if (res.data.size === 0) {
      if (that) {
        message.error('导出失败');
      }
      if (that.downLoading) {
        that.downLoading = false
      }
      return
    }
    if (res.data.type === 'application/json') {
      var reader = new FileReader()
      reader.onload = function (e) {
        var content = reader.result
        if (that) {
          message.error(content);
        }
      }
      reader.readAsText(res.data)
      if (that.downLoading) {
        that.downLoading = false
      }
      return
    }
    const link = document.createElement('a')
    let blob = new Blob([res.data], {type: 'multipary/form-data;charset=utf-8'})
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)

    // 文件名没有给出
    // if (fileName.indexOf('.') < 0) {
    //   let headerFileName = res.headers['content-disposition']
    //   if (headerFileName) {
    //     headerFileName = headerFileName.split('=')[1]
    //     fileName = fileName + headerFileName.substr(headerFileName.lastIndexOf('.'))
    //   }
    // }
    let headerFileName = res.headers['content-disposition']
    if (headerFileName) {
      headerFileName = headerFileName.split('=')[1]
      let iconv = require('iconv-lite')
      iconv.skipDecodeWarning = true
      fileName = iconv.decode(headerFileName, 'utf8')
    }
    link.setAttribute('download', decodeURI(fileName))
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    if (that) {
      if (that.downLoading) {
        that.downLoading = false
      }
      message.success('导出成功');
    }
  })
}

export default http
